const {
    gets,
    post,
    del,
    put
} = require('/config/request.js');
const router = require("/config/router.js")
const store = require("/config/store.js")

const {
    $on,
    $emit,
    $remove
} = require("/config/event.js")

const { LOGIN, LOCATION } = require("/config/login.js")
const { Dialog } = require("/config/modal")
const utils = require("/utils/util")
/**
 * "disableScroll": true 禁止手机下拉
 */
App({
    onLaunch() {
        this.checkVersionUpdate();
        this.$initServerCommonInfo();
        this.setNavBar();
        this.startDongTai();
        this.startMp();
    },

    checkVersionUpdate() {
        if (wx.canIUse('getUpdateManager')) {
            const updateManager = wx.getUpdateManager()
            updateManager.onCheckForUpdate(function (res) {
                console.log('onCheckForUpdate====', res)
                // 请求完新版本信息的回调
                if (res.hasUpdate) {
                    console.log('res.hasUpdate====')
                    updateManager.onUpdateReady(function () {
                        wx.showModal({
                            title: '更新提示',
                            content: '新版本已经准备好，是否重启应用？',
                            success: function (res) {
                                console.log('success====', res)
                                // res: {errMsg: "showModal: ok", cancel: false, confirm: true}
                                if (res.confirm) {
                                    // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                                    wx.clearStorage();
                                    updateManager.applyUpdate()
                                }
                            }
                        })
                    })
                    updateManager.onUpdateFailed(function () {
                        console.log('fail====', res)
                        // 新的版本下载失败
                        wx.showModal({
                            title: '已经有新版本了哟~',
                            content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~'
                        })
                    })
                }
            })
        }
    },
    globalData: {
        // 记录第一次进来的上一页地址，防止来回编辑后，页面栈全是这两个，导致返回不去
        preFirstPathKey: 'preFirstPath',
        window: {
            navHeight: 0,
            navTop: 0,
            tabbarHeight: 0,
            windowHeight: 0,
            contentHeight: 0,
            screenHeight: 0,
            windowWidth: 0,
        },
        serverCommonInfo: null,
        theamTextColor: "#CB6024",
        URL: {
            concatMeInfo: "/common/concatMeInfo",
            startDongTai: "/common/isStart",
            startMp: "/common/startMp",
        },
        actionFlag: false,
        startMp: false,
    },

    startDongTai() {
        this.$get(false, this.globalData.URL.startDongTai, {}, res => {
            if (res.R) {
                this.globalData.actionFlag = res.data
            }
        })
    },
    startMp() {
        this.$get(false, this.globalData.URL.startMp, {}, res => {
            if (res.R) {
                this.globalData.startMp = res.data
            }
        })
    },
    $getActionFlag() {
        return this.globalData.actionFlag;
    },
    $isStartMp() {
        return this.globalData.startMp;
    },

    $initServerCommonInfo() {
        if (this.globalData.serverCommonInfo != null) {
            return;
        }
        this.$get(false, this.globalData.URL.concatMeInfo, {}, res => {
            if (res.R) {
                let inviteBgImg = "/static/img/yello.jpeg";
                res.data['inviteBgImg'] = "/static/img/yello.jpeg";
                this.globalData.serverCommonInfo = res.data
            }
        })
    },
    $getServerCommonInfo() {
        return this.globalData.serverCommonInfo
    },


    setNavBar() {
        let menuButtonObject = wx.getMenuButtonBoundingClientRect();

        wx.getSystemInfo({
            success: res => {

                // 整个小程序导航栏高度
                this.globalData.window.navHeight = res.statusBarHeight + menuButtonObject.height + (menuButtonObject.top - res.statusBarHeight) * res.pixelRatio;
                ;

                // 窗口高度
                this.globalData.window.navTop = menuButtonObject.top;
                // 窗口高度
                this.globalData.window.windowHeight = res.windowHeight;

                // 内容高度
                this.globalData.window.contentHeight = res.windowHeight - this.globalData.window.navHeight;

                this.globalData.window.model = res.model;
                // 底部状态栏的高度
                this.globalData.window.tabbarHeight = (res.screenHeight - this.globalData.window.contentHeight - this.globalData.window.navHeight);
                this.globalData.window.screenHeight = res.screenHeight;
                this.globalData.window.windowWidth = res.windowWidth;

                // console.log("window", this.globalData.window)
                // console.log("systemInfo", res)

                // console.log("整个导航栏高度：navHeight", this.globalData.navHeight)
                // console.log("statusBarHeight", this.globalData.statusBarHeight)
                // console.log("menuButtonObject.height", menuButtonObject.height)
                // console.log("胶囊栏的高度：menuButtonObject.top", menuButtonObject.top)
                // console.log("整个手机屏幕高度：windowHeight", res.windowHeight)

            },
            fail(err) {
                console.log(err);
            }
        })
    },

    // -------------1、封装请求-------------
    $delete: function (loading, url, data, callback) {
        del(loading, url, data, null, callback)
    },

    $get: function (loading, url, data, callback) {
        gets(loading, url, data, null, callback)
    },

    $post: function (loading, url, data, callback) {
        post(loading, true, url, data, null, callback)
    },
    $postIsTip: function (loading, isTip, url, data, callback) {
        post(loading, isTip, url, data, null, callback)
    },

    $put: function (loading, url, data, callback) {
        put(loading, url, data, null, callback)
    },


    // alert --------------------------------
    $alert: function (msg) {
        Dialog.alert({
            message: msg,
            width: "270px",
            confirmButtonColor: "#D2691E",
            confirmButtonText: "关闭",
        })
    },
    $alertConfirm: function (e) {
        let options = {
            title: utils.isInvalid(e.title) ? '友情提示' : e.title,
            message: e.msg,
            width: "280px",
            confirmButtonColor: utils.isInvalid(e.confirmButtonColor) ? '"#D2691E"' : e.confirmButtonColor,
            confirmButtonText: utils.isInvalid(e.sureMsg) ? '确定' : e.sureMsg,
            showCancelButton: true,
            confirmButtonOpenType: utils.isInvalid(e.sureMsg) ? '' : e.openType,
            cancelButtonText: utils.isInvalid(e.cancelMsg) ? '取消' : e.cancelMsg,
        }
        Dialog.alert(options).then(() => {
            if (!utils.isInvalid(e.success())) {
                e.success()
            }
        }).catch(() => {
            if (!utils.isInvalid(e.cancel)) {
                e.cancel()
            }
        });
    },
    // alert --------------------------------

    // -----------2、路由封装，拦截---------
    $router(page, isAuth, type) {
        router.routerAuth(page)
    },
    $navigateTo(page, isAuth) {
        router.routerAuth(page, isAuth, "nTo")
    },


    /**
     * 跳转到授权页面
     * @param params 携带参数；带什么参数去，授权之后带什么回来
     */
    $navigateToAuth(params) {
        let path = "/pages/noAuth/index";
        path = utils.paramsToPathParams(params, path);
        router.routerAuth(path, false, "nTo")
    },

    $switchTab(page, isAuth) {
        router.routerAuth(page, isAuth, "tab")
    },
    $redirectTo(page, isAuth) {
        router.routerAuth(page, isAuth, "rTo")
    },

    // ----------3、用户信息操作-----------
    $isAuth() {
        return LOGIN.isAuthLogin();
    },


    $isAuthLocation() {
        return LOCATION.isAllowedLocation();
    },
    $getAuthorization() {
        return store.getAuthorization();
    },
    $getUserInfo() {
        return store.getUserInfo()
    },
    $saveUserInfo(data) {
        return store.saveUserInfo(data)
    },
    $saveData(key, data) {
        return store.saveData(key, data)
    },
    $getData(key) {
        return store.getData(key)
    },
    $saveFromPath(key, path) {
        let from = this.$getFromPath(key);
        if (utils.isInvalid(from)) {
            store.saveData(key, path)
        }
    },
    $getFromPath(path) {
        return store.getData(path)
    },
    $removeStore(key) {
        wx.removeStorageSync(key);
    }
    // ----------4、全局事件监听----------
    ,
    $on(name, tg, callback) {
        //接收消息 传入params={name:"string 监听事件名",success:"function 监听事件回调",tg:"当前页面或App.js  传入this即可"}
        $on({
            name: name,
            tg: tg,
            success: callback
        })
    },
    $emit(name, data) {
        //消息发送 传入{name:"string 发送消息事件名",data:"可选  可以是任意数据类型"}
        $emit({
            name: name,
            data: data
        })
    },
    $remove(name, tg) {
        //移除监听  传入params={name:"string 监听事件名",tg:"当前页面或App.js  传入this即可"}
        $remove({
            name: name,
            tg: tg
        })
    }
    // 获取胶囊额导航栏的高度
    , $getMenuButtonHeight() {
        let menu = wx.getMenuButtonBoundingClientRect();
        let capsuleBarHeight = menu.height - 2;
        // capsuleBarHeight=utils.px2rpx(capsuleBarHeight);
        // console.log(`CapsuleBar 的高度为${capsuleBarHeight}px`)
        return capsuleBarHeight
    },

    // 处理邀请码
    $handlerInviteCode(options) {
        let invitees = options.invitees;

        console.log("检查邀请人", utils.isInvalid(invitees) ? options.q : invitees)

        // 邀请码
        if (!utils.isInvalid(invitees)) {
            console.log("保存邀请人", invitees)
            this.$saveData('invitees', invitees);
            if (this.$isAuth()) {
                this.$postIsTip(false, false, "/customer/updateInvitees", { invitees: invitees }, res => {
                    console.log("更新邀请人", invitees, res.msg)
                    if (res.R) {
                        let userInfo = this.$getUserInfo();
                        userInfo.invitees = invitees;
                        this.$saveUserInfo(userInfo);
                        this.$removeStore('invitees');
                    }
                })
            }
        } else {
            if (utils.isInvalid(options.q)) {
                return;
            }
            debugger
            let q = decodeURIComponent(options.q);
            invitees = utils.getQueryString(q, 'invitees');

            console.log('扫描二维码进入传递的参数', invitees)
            console.log("保存邀请人", invitees)

            this.$saveData('invitees', invitees);
            if (this.$isAuth()) {
                this.$postIsTip(false, false, "/customer/updateInvitees", { invitees: invitees }, res => {
                    console.log("更新邀请人", invitees, res.msg)
                    if (res.R) {
                        let userInfo = this.$getUserInfo();
                        userInfo.invitees = invitees;
                        this.$saveUserInfo(userInfo);
                        this.$removeStore('invitees');
                    }
                })
            }
        }
    },
    $onShare(url, params, title) {
        let inviteCode = this.$getUserInfo().inviteCode;
        console.log("分享给他人,我的邀请码", utils.isInvalid(inviteCode) ? "无邀请码" : inviteCode)
        let path = url + "?invitees=" + (utils.isInvalid(inviteCode) ? "" : inviteCode) + (utils.isInvalid(params) ? "" : params);
        //console.log("share path：" + path)
        return {
            title: utils.isInvalid(title) ? "校园CBD" : title,
            path: path
        }
    }
})
// ,{
//     "pagePath": "pages/tabbar/tbk/index",
//     "text": "购物券",
//     "iconPath": "/static/tabar-icon/quan.png",
//     "selectedIconPath": "/static/tabar-icon/quan-selected.png"
// },